<?php
/**
 * Created by PhpStorm.
 * User: drapeo
 * Date: 2015/5/11
 * Time: 21:41
 */
/**
 * @param int $db  default 4
 * @return Redis
 */
function getRedis($db=4)
{
    $GLOBALS['redis'][$db];
    if(!$GLOBALS['redis'][$db])
    {
        $GLOBALS['redis'][$db] = new Redis();
        $GLOBALS['redis'][$db]->connect(C('REDIS_HOST'), C('REDIS_PORT'));
        $GLOBALS['redis'][$db]->auth(C('REDIS_PASSWORD'));
        $GLOBALS['redis'][$db]->select($db);
    }
    return $GLOBALS['redis'][$db];
}


//更新U站点附件配置
function updateUploadAttach($data){
    return \Common\Org\Attach\Attach::get_attach($data);
}

/**
 * 获取附件配置
 * @param $alias 附件配置别名
 * @param string $uid 用户ID，美容院ID，厂商ID
 */
function get_attach($alias,$uid=''){
    if(empty($alias)) return false;

    $_attachList = C('ADJUNC_CONFIG');
    if(empty($_attachList)) return false;

    $_attach = $_attachList[$alias];
    if(empty($_attach)) return false;

    if(!empty($uid)){
        $spaceDir = 'User';
        $root_img_path = rtrim(C("TMPL_PARSE_STRING.__IMG__"),'/').'/'.$spaceDir.'/'.$uid.'/'.trim($_attach['dir_path'],'/').'/'.ceil($uid/30000) .'/';
    } else {
        $root_img_path = rtrim(C("TMPL_PARSE_STRING.__IMG__"),'/').'/Admin/'.trim($_attach['dir_path'],'/').'/';
    }

    $_attach['img_root'] = $root_img_path;

    return $_attach;
}

//获取附件配置
function get_manage_attach($alias){
    return get_attach($alias);
}

function getMemcached(){
    static $m;
    if(!$m){
        $m = new \Think\Cache\Driver\Memcache();
    }

    return $m;
}

/**
 * tf函数用于过滤标签，输出没有html的干净的文本
 * @param string text 文本内容
 * @return string 处理后内容
 * 20140410 添加
 */
function tf($text){
    $text = nl2br($text);
    $text = real_strip_tags($text);
    $text = addslashes($text);
    $text = trim($text);
    return $text;
}

function real_strip_tags($str, $allowable_tags="") {
    $str = html_entity_decode($str,ENT_QUOTES,'UTF-8');
    return strip_tags($str, $allowable_tags);
}

//获取path最后点id
function get_path_last_id($path)
{
    $id = 0;
    if($path)
    {
        $temp = explode('-',$path);
        $id = array_pop($temp);
        unset($temp);
    }
    return $id;
}

/**
 *
 * 正则替换和过滤内容
 *
 * @param  $html
 * @author jason
 */
function preg_html($html){
    $p = array("/<[a|A][^>]+(topic=\"true\")+[^>]*+>#([^<]+)#<\/[a|A]>/",
        "/<[a|A][^>]+(data=\")+([^\"]+)\"[^>]*+>[^<]*+<\/[a|A]>/",
        "/<[img|IMG][^>]+(src=\")+([^\"]+)\"[^>]*+>/");
    $t = array('topic{data=$2}','$2','img{data=$2}');
    $html = preg_replace($p, $t, $html);
    $html   = strip_tags($html,"<br/>");
    return $html;
}

//解析数据成网页端显示格式
function parse_html($html){
    $html = htmlspecialchars_decode($html);
    //以下三个过滤是旧版兼容方法-可屏蔽
    $html = preg_replace("/img{data=([^}]*)}/"," ", $html);
    $html = preg_replace("/topic{data=([^}]*)}/",'<a href="$1" topic="true">#$1#</a>', $html);
    $html = preg_replace_callback("/@{uid=([^}]*)}/", "_parse_at_by_uid", $html);
    //链接替换
    $html = str_replace('[SITE_URL]',SITE_URL,$html);
    //外网链接地址处理
    //$html = preg_replace_callback('/((?:https?|ftp):\/\/(?:www\.)?(?:[a-zA-Z0-9][a-zA-Z0-9\-]*\.)?[a-zA-Z0-9][a-zA-Z0-9\-]*(?:\.[a-zA-Z0-9]+)+(?:\:[0-9]*)?(?:\/[^\x{2e80}-\x{9fff}\s<\'\"“”‘’,，。]*)?)/u', '_parse_url', $html);
    //表情处理
    $html = preg_replace_callback("/(\[.+?\])/is",_parse_expression,$html);
    //话题处理
    $html = str_replace("＃", "#", $html);
    $html = preg_replace_callback("/#([^#]*[^#^\s][^#]*)#/is",_parse_theme,$html);
    //@提到某人处理
    $html = preg_replace_callback("/@([\w\x{2e80}-\x{9fff}\-]+)/u", "_parse_at_by_uname",$html);

    return $html;
}

/**
 * 获取字符长度
 * @param $str 字符串
 * @param $mode 模式，1=一个英文字符占一个长度单位，2=两个英文字符占一个长度单位，
 * 比如：echo abslength('ssss',1);//print 4
 * 比如：echo abslength('ssss',2);//print 2
 * @return int
 */
function abslength($str,$mode=2) {
    if(empty($str)){
        return 0;
    }
    if(function_exists('mb_strlen')){
        if($mode==1){
            return mb_strlen($str,'utf-8');
        } else {
            return ceil((strlen($str) + mb_strlen($str, 'UTF8')) / 4);
        }
    } else {
        if($mode==1){
            preg_match_all("/./u", $str, $ar);
            return count($ar[0]);
        } else {
            mb_regex_encoding('utf-8');
            $str = mb_ereg_replace('[\xa0-\xff]','aa',$str);//替换中文（双字节字符）为2个字符（单字节字符）
            return ceil(strlen($str)/2);
        }
    }
}

/*
 * 去除html标签
 */
function clear_html_label($html){
    $search = array ("'<script[^>]*?>.*?</script>'si",
        "'<[/!]*?[^<>]*?>'si",
        //"'([rn])[s]+'",
        "'&(quot|#34);'i", "'&(amp|#38);'i",
        "'&(lt|#60);'i",
        "'&(gt|#62);'i",
        "'&(nbsp|#160);'i",
        "'&(iexcl|#161);'i",
        "'&(cent|#162);'i",
        "'&(pound|#163);'i",
        "'&(copy|#169);'i",
        "'&#(d+);'e");
    $replace = array ("", "", "1", "\"", "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), "chr(1)");
    return preg_replace($search, $replace, $html);
}
/*
 * html过滤
 */
function filterHtml($html){
    $html = clear_html_label($html);
    $js ="/<script[^>]*?>.*?<\/script>/si";
    $str = preg_replace($js,' ',$html);
    $css = "/<style[^>]*?>.*?<\/style>/si";
    $str = preg_replace($css,' ',$str);

    return $str;
}
/**
 * 敏感词过滤
 */
function filterkeyword($html){
    static $audit  =null;
    static $auditSet = null;
    if($audit == null){ //第一次
        $audit = D('Xdata')->get('keywordConfig');
        $audit = explode(',',$audit);
        $auditSet =  D('Xdata')->get('admin_Config:audit');
    }
    // 不需要替换
    if(empty($audit) || $auditSet['open'] == '0'){
        return $html;
    }

    return str_replace($audit, $auditSet['replace'], $html);
}
/**
 * 检查字符串是否是UTF8编码
 * @param string $string 字符串
 * @return Boolean
 */
function is_utf8($string) {
    return preg_match('%^(?:
         [\x09\x0A\x0D\x20-\x7E]            # ASCII
       | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
       |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
       | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
       |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
       |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
       | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
       |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
    )*$%xs', $string);
}
/**
 * 敏感词过滤(弹出敏感词)
 * @param $str 内容
 * @return string
 */
function getKeywords($str){
    $audit = D('Xdata')->get('keywordConfig');
    $arr = explode(',',$audit);
    $return = array();
    foreach($arr as $v){
        if(strpos($str,$v)!==false) {
            $return[] = $v;
        }
    }
    return implode(',',$return);
}

/**
 * 检测验证码
 * @param $code
 * @param int $id
 * @return bool
 */
function check_verify($code, $id = 1){
    $verify = new \Think\Verify();

    $res = $verify->check($code, $id);

    return $res;
}

/**
 * @return \Common\Model\InputData
 * 获取数据验证类实例
 */
function getInputData(){
    static $input;
    if(!$input) {
        $input = new \Common\Org\Util\InputData();
    }
    return $input;
}

/**
 * 邮件处理
 * @param $email 邮件
 * @return string
 */
function explodeEmail($email){
    if(empty($email)) return false;
    $arr = explode('@',$email);

    $val = explode('.',$arr[1]);
    if($val[0]=='sina'){
        $str ='mail.sina.com.cn';
    }else{
        $str ='mail.'.$arr[1];
    }
    return 'http://'.$str;
}

/**
 * 自动闭合html标签
 */
function closetags($html) {
    preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];

    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);

    if (count($closedtags) == $len_opened) {
        return $html;
    }
    $openedtags = array_reverse($openedtags);

    for ($i=0; $i < $len_opened; $i++) {
        if (!in_array($openedtags[$i], $closedtags)){
            $html .= '</'.$openedtags[$i].'>';
        } else {
            unset($closedtags[array_search($openedtags[$i], $closedtags)]);
        }
    }
    return $html;
}

function curlencode($str){
    $str = urlencode($str);
    return str_replace('+','%20',$str);
}

/**
 * @param $url
 * @return bool
 * 验证远程文件是否存在
 */
function check_remote_file_exists($url) {
    $curl = curl_init($url);

    //不取回数据
    curl_setopt($curl, CURLOPT_NOBODY, true);
    //发送请求
    $result = curl_exec($curl);
    $found = false;
    if ($result !== false) {
        //检查http响应码是否为200
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($statusCode == 200) {
            $found = true;
        }
    }
    curl_close($curl);
    return $found;
}

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-6-13
 * Time: 下午1:57
 * 获取签名
 */
function get_signature($str, $key)
{
    $signature = "";
    if (function_exists('hash_hmac'))
    {
        $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
    }
    else
    {
        $blocksize	= 64;
        $hashfunc	= 'sha1';
        if (strlen($key) > $blocksize)
        {
            $key = pack('H*', $hashfunc($key));
        }
        $key	= str_pad($key,$blocksize,chr(0x00));
        $ipad	= str_repeat(chr(0x36),$blocksize);
        $opad	= str_repeat(chr(0x5c),$blocksize);
        $hmac 	= pack(
            'H*',$hashfunc(
                ($key^$opad).pack(
                    'H*',$hashfunc(
                        ($key^$ipad).$str
                    )
                )
            )
        );
        $signature = base64_encode($hmac);
    }
    return $signature;
}

/**
 * @return string
 * URL及参数处理
 */
function params_deal($host,$params=null){
    if($params==null) $params = $_REQUEST;
    $array = $params;
    unset($array['sig']);
    ksort($array);
    $host =  \Common\Org\Sms\OAuthUtil::urlencode_rfc3986($host);
    $key = $host.'&'.\Common\Org\Sms\OAuthUtil::build_http_query($array);
    return $key;
}

/**
 * @param $akey
 * @param $skey
 * @return string
 * 获取密钥
 */
function get_secret($akey,$skey){
    return md5($akey).md5($skey).md5($akey.$skey);
}

/*
 * 手机格式化输出
 */
function mobileFormat($mobile){
    if(!preg_match(\Common\Org\Util\InputData::$mobile_reg,$mobile)){
        return false;
    }

    for($i=0;$i<strlen($mobile);$i++){
        if($i>=3 && $i<=6 ){
            $mobile[$i]='*';
        }
    }
    return $mobile;
}

function telRegx($tel){
    if(!preg_match(\Common\Org\Util\InputData::$tel_reg,$tel)){
        return false;
    }
    return true;
}

function generateApiKey()
{
    return md5(time()).md5(uniqid()).md5(time().uniqid()).md5(mt_rand(1,100000));
}

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr"))
        $slice = mb_substr($str, $start, $length, $charset);
    elseif(function_exists('iconv_substr')) {
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false === $slice) {
            $slice = '';
        }
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    if(abslength($str) < $length) $suffix = false;
    return $suffix ? $slice.'...' : $slice;
}

/**
 * @param $obj
 * @return bool
 * 判断是否为空
 */
function isEmpty($obj){
    if(is_scalar($obj)){
        return $obj==''?true:false;
    } else if(is_array($obj)){
        return count($obj)==0?true:false;
    } else {
        return !$obj?true:false;
    }
}

function sinadwz($url,$boot=false){
    $sina_config = D('Admin/ThirdPlatformSet')->getThirdPlatformConfig('sina');
    $client = new \Common\Org\Sms\HttpClient();
    $ret = $client->get('http://api.t.sina.com.cn/short_url/shorten.json',array('source'=>$sina_config['key'],'url_long'=>$url));
    $ret = json_decode($ret);
    $ret = get_object_vars($ret[0]);

    if(!empty($ret['url_short'])) {
        $url = $ret['url_short'];
    }
    if($boot){
        return $url;
    }else{
        return '<a href="'.$url.'" class="blue">'.$url.'</a>';
    }
}

//获取短网址
function dwz($url,$boot=false) {
    return sinadwz($url,$boot);
}

//将发布内容中网址转为短网址
function changeUrl($content){
    return  preg_replace_callback('/(https?:\/\/){1}([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?/','dwz',$content);
}

//截取长度||单位为一个汉字长度
function cut_str($string, $length, $dot_html = '...') {
    $search = array ("'<script[^>]*?>.*?</script>'si","'<style[^>]*?>.*?</style>'si","'<[/!]*?[^<>]*?>'si","'<!--[/!]*?[^<>]*?>'si","'([rn])[s]+'","'&(quot|#34);'i","'&(amp|#38);'i","'&(lt|#60);'i","'&(gt|#62);'i","'&(nbsp|#160);'i","'&(iexcl|#161);'i","'&(cent|#162);'i","'&(pound|#163);'i","'&(copy|#169);'i","'&#(d+);'e");
    $replace = array ("","","","","\1","\"","&","<",">"," ",chr(161),chr(162),chr(163),chr(169),"chr(\1)");
    $dot = preg_replace($search, $replace, $dot_html);

    $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '"', '"', '—', '<', '>', '·', '…'), $string);
    $length = $length*2;
    $dot = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '"', '"', '—', '<', '>', '·', '…'), $dot);
    $strcut = '';
    $n = $dot_length = 0;
    while ($n < strlen($dot)) {
        $t = ord($dot[$n]);
        if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $n++; $dot_length++;
        } elseif(194 <= $t && $t <= 223) {
            $n += 2; $dot_length += 2;
        } elseif(224 <= $t && $t <= 239) {
            $n += 3; $dot_length += 2;
        } elseif(240 <= $t && $t <= 247) {
            $n += 4; $dot_length += 2;
        } elseif(248 <= $t && $t <= 251) {
            $n += 5; $dot_length += 2;
        } elseif($t == 252 || $t == 253) {
            $n += 6; $dot_length += 2;
        } else {
            $n++;
        }
    }
    $n = $tn = $noc = 0;
    $strlen = strlen($string);
    while ($n < $strlen) {
        $t = ord($string[$n]);
        if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1; $n++; $noc++; $dot_length++;
        } elseif(194 <= $t && $t <= 223) {
            $tn = 2; $n += 2; $noc += 2; $dot_length += 2;
        } elseif(224 <= $t && $t <= 239) {
            $tn = 3; $n += 3; $noc += 2; $dot_length += 2;
        } elseif(240 <= $t && $t <= 247) {
            $tn = 4; $n += 4; $noc += 2; $dot_length += 2;
        } elseif(248 <= $t && $t <= 251) {
            $tn = 5; $n += 5; $noc += 2; $dot_length += 2;
        } elseif($t == 252 || $t == 253) {
            $tn = 6; $n += 6; $noc += 2; $dot_length += 2;
        } else {
            $n++;
        }
        if ($dot_length >= $length){
            if (!isset($d)) {
                $d = $n;
                $dn = $tn;
                $dotlen = $dot_length;
            }
        }
        if ($noc >= $length) {
            break;
        }
    }
    $dot_state = $n<$strlen;
    if ($dot_state) {
        $n = $d;
        $tn = $dn;
        $noc = $dotlen;
    }
    if ($noc > $length) {
        $n -= $tn;
    }
    $strcut = substr($string, 0, $n);
    $strcut = str_replace(array('∵', '&', '"', "'", '"', '"', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
    if ($dot_state) {
        $strcut = $strcut.$dot_html;
    }
    return $strcut;
}

function toDate($time, $format = 'Y-m-d H:i:s') {
    if (empty ( $time )) {
        return '';
    }
    $format = str_replace ( '#', ':', $format );
    return date ($format, $time );
}

/**
 * 去除空格（左中右）
 * @param $str
 * @return bool|mixed
 */
function clearSpance($str){
    if(empty($str)) return false;
    $str = trim($str);
    return preg_replace('# #', '', $str);
}

/**
 * 将表中数据导出为EXCEL
 * $title_arr 为表头内容，数组形式
 * $data_arr 为表中的数据集合
 */
function toExcel($title_arr,$data_arr='',$title='',$operater=''){
    import("Common/Org/PHPExcel/PHPExcel");
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel ->getProperties()
        ->setCreator($operater)
        ->setTitle($title);
    //表头写入
    $words = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    foreach($title_arr as $key=>$val){
        if($key==26) return;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($words[$key].'1', $val);
    }

    //数据的写入
    foreach($data_arr as $key=>$val){
        $n=0;
        foreach($val as $key2=>$val2){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($words[$n].($key+2), $val2);
            $n++;
        }
    }

    //设置一列的宽度
    $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(13);

    $objPHPExcel->setActiveSheetIndex(0);
    //处理文件名，防止中文出现乱码
    $title = $title.'.xls';
    $filename = urlencode($title);
    $filename = str_replace('+','%20',$filename);

    $ua = $_SERVER["HTTP_USER_AGENT"];
    header('Content-Type: application/vnd.ms-excel');
    if(preg_match("/MSIE/", $ua)) {
        header('Content-Disposition: attachment; filename="' . $filename . '"');
    }else if(preg_match("/Firefox/", $ua)) {
        header('Content-Disposition: attachment; filename*="utf8\'\'' . $title . '"');
    }else{
        header('Content-Disposition: attachment; filename="' . $title . '"');
    }
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}

/**
 * 价格转化函数，保留两位小数
 * @param $price
 */
function convertPrice($price){
    if(is_string($price) && strpos($price,'~')!==false){
        $pos = strpos($price,'~');
        if($pos==0 || $pos==strlen($price)) return '0.00';
        $arr = explode('~',$price);
        if(count($arr)!=2) return '0.00';
        return implode('~',array_map('convertPrice',$arr));
    } else {
        if(is_numeric($price)){
            return sprintf("%01.2f", $price);
        } else {
            return '0.00';
        }
    }
}

/**
 * 判断价格是否合法
 * @param $price 要判断的价格
 * @param $zeroAllow 是否允许零价格
 * @return bool
 */
function isRegularPrice($price,$zeroAllow=false){
    if(is_numeric($price) && preg_match('/^\d*(\.\d{0,2})?$/',$price)){
        if(!$zeroAllow && empty($price)) return false;
        if($price<0 || $price>999999999.99){
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

/**
 * 获取图片的完整URL
 * @param $img 图片文件名
 * @param $alias 附件配置别名
 * @param $size 尺寸大小
 * @param int $returnType 返回类型，1=返回数组，2=返回字符串
 */
function getImgUrl($img,$uid='',$alias,$size=1,$returnType=1){
    if(empty($img) || empty($alias)) return '';

    $imgArr = explode(',',$img);

    $attach = get_attach($alias,$uid);
    if(empty($attach)) return '';

    $prefix = getAttachPrefix($attach['extend'],$size);
    $imgPrefix = $attach['img_root'].$prefix;

    foreach($imgArr as &$url){
        $url = $imgPrefix.$url;
    }

    if($returnType==1){
        return $imgArr;
    } else {
        return implode(',',$imgArr);
    }
}

function getAttachPrefix($extend,$size=1){
    if(empty($extend)) return '';

    $i = 0;
    $extendArr = explode('|',$extend);//标准尺寸
    $prefix = '';

    foreach($extendArr as $val){
        if(($i+1) == $size){
            $prefix = ($i+1).'_';;
            break;
        }
        $i++;
    }

    return $prefix;
}

/**
 * 清理其他标签
 * @param $str
 * @return mixed
 */
function clearOtherTag($str){
    if(empty($str)) return false;
    $arr= array("\n", "\r", "\r\n","\t\t","\t","&nbsp;");
    $str=str_replace($arr,"",tf($str));
    return $str;
}

function toErrorPage(){
    if(MODULE_NAME == 'Wap'){
        redirect('/Index/index');
    }else{
        redirect('/Public/epage');
    }
    exit;
}

/**
 * 数据正则验证
 * @param $regx 正则表达式
 * @param $str 验证的字符串
 * @return bool
 */
function checkRegx($regx,$str){
    if(!preg_match($regx, $str)){
        return false;
    }
    return true;
}

/**
 * 发送短信
 * @param $mobile 发送手机号
 * @param $alias 模板别名
 * @param $data 替换数据
 * @return bool
 */
function sendSms($mobile,$alias,$data){
    if(empty($mobile) || empty($alias)) return false;
    return D('SmsSend')->sendSMS($mobile,'+86',$alias,$data);
}

/**
 * 发送邮件
 * @param $email 发送的邮件
 * @param $title 邮件主题
 * @param $alias 模板别名
 * @param array $data 替换的数据
 * @return string
 */
function sendEmail($email,$alias,$data=array(),$title = '爪爪鱼'){
    if(empty($email) || empty($alias)){
        return '参数错误！';
    }

    $mail = new \Common\Org\Email\Email();
    $obj = $mail::getInstance(2);
    $obj->setEmail($email);
    $_data = M('system_template')->where(array('alias'=>$alias))->find();
    if($title == ''){
        $obj->setThem($_data['title']);
    }else{
        $obj->setThem($title);
    }


    //TP模板解析
    $tpl = \Think\Think::instance('Think\\Template');
    // 编译并加载模板文件
    ob_start();
    ob_implicit_flush(0);
    $tpl->fetch($_data['content'],$data,'');
    $body = ob_get_clean();
    $body = str_replace("{SITE_NAME}",SITE_NAME,$body); //替换模板中的变量

    $obj->setBody($body);
    if(!$obj->sendEmail()){
        return false;
    }else{
        return true;
    }
}

/**
 * @return string
 * 公共JS变量加载
 */
function commonJs(){
    $DOMAIN_SUFFIX = DOMAIN_SUFFIX;
    $PUBLIC = C('TMPL_PARSE_STRING.__PUBLIC__');
    $MAINHOST = C('TMPL_PARSE_STRING.__HOME__');
    $FILEHOST = C('TMPL_PARSE_STRING.__FILE__');
    return '<script type="text/javascript">
                var PUBLIC = "'.$PUBLIC.'";
                var MAINHOST = "'.$MAINHOST.'";
                var DOMAIN_SUFFIX = "'.$DOMAIN_SUFFIX.'";
                var FILEHOST = "'.$FILEHOST.'";
                var SITE_NAME = "'.SITE_NAME.'";
            </script>';
}

/**
 * 发送单条系统消息
 * @param $content 内容
 * @param $uid 用户uid
 * @param $urlDesc url描述
 * @return bool
 */
function sendNotice($content,$uid,$urlDesc='',$order_id='',$type=1){
    if(empty($content) || empty($uid)) return false;
    $data = array(
        'uid'=>$uid,
        'title'=>$content,
        'url'=>$urlDesc,
        'add_time'=>time(),
        'is_read'=>2,
        'order_id'=>$order_id,
        'type'=>$type
    );
    D('Common/UserMsg')->sendMsg($data);
}

/**
 * 生成随机数字符串
 */
function generateRandomStr(){
    $random = mt_rand(0,99999999);

    return md5($random);
}

/**
 * 生成微信签名
 * @param $param
 */
function generateWechatSign($param){
    if(empty($param)) return '';
    unset($param['sign']);
    ksort($param);

    $temp = array();
    foreach($param as $key=>$val){
        if(empty($val)) continue;
        $temp[] = trim($key).'='.trim($val);
    }
    $temp[] = 'key='.C('KEY');

    $str = implode('&',$temp);

    return strtoupper(md5($str));
}

/**
 * 计算时间相差天数
 * @param $begin_time 开始时间
 * @param $end_time 最后时间
 * @return array
 */
function timediff( $begin_time, $end_time ){
    if ( $begin_time < $end_time ) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime - $starttime;
    $days = intval( $timediff / 86400 );
    $remain = $timediff % 86400;
    $hours = intval( $remain / 3600 );
    $remain = $remain % 3600;
    $mins = intval( $remain / 60 );
    $secs = $remain % 60;
    $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
    return $res;
}

/**
 * 判断是否为浮点数
 * @param $num 要判断的价格
 * @return bool
 */
function isFloatNum($num,$digit=2){
    if(is_numeric($num) && preg_match('/^\d*(\.\d{0,'.$digit.'})?$/',$num)){
        if($num<0 || $num>999999999.99){
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

/**
 * 判断是否正确的百分比
 * @param $percentage
 * @param int $digit
 * @return bool
 */
function isRegularPercentage($percentage,$digit=3){
    if(!preg_match('/^\d*(\.\d{0,'.$digit.'})?%$',$percentage)){
        if(strlen($percentage)>10){
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

/**
 * 分数正则
 * @param $score 分数
 * @return bool
 */
function scoreRegx($score){
    if(checkRegx("/^[0-9]|[0-9].[1-9]/",$score)){
        return true;
    }else{
        return false;
    }
}

/**
 * 根据生日计算年龄
 * @param $birthday
 * @return bool|int
 */
function birthday($birthday){
    $age = $birthday;
    if($age === false){
        return false;
    }
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
    $now = strtotime("now");
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
    $age = $y2 - $y1;
    if((int)($m2.$d2) < (int)($m1.$d1))
        $age -= 1;
    return $age;
}

function searchArray($keyword,$arr){
    $res_arr = array();
    foreach($arr as $key=>$val){
        if(preg_match('/^'.$keyword.'/',$key)){
            $res_arr[$key] = $val;
        }
    }
    return $res_arr;
}

/**
 * 获取星期天数
 * @param $time
 * @return string
 */
function getWeekDate($time){
    if(empty($time)) return false;
    $weekarray=array("日","一","二","三","四","五","六");
    return "星期".$weekarray[date("w",$time)];
}

/**
 * 获取文件的后缀
 * @param $filename
 * @return string
 */
function fileSuffix($filename){
    if(empty($filename)) return false;
    return strtolower(trim(substr(strrchr($filename, '.'), 1)));
}

/**
 * 判断是否为图片
 * @param $filename
 * @return bool
 */
function isImage($filename){
    if(empty($filename)) return false;
    $suffix = fileSuffix($filename);
    $imgSuffixArr = array('jpg','png','jpeg','bmp');
    if(in_array($suffix,$imgSuffixArr)){
        return true;
    }else{
        return false;
    }
}

/**
 * 判断是否为微信浏览器
 * @return bool
 */
function isWeiXinBrowser(){
    if(strpos($_SERVER['HTTP_USER_AGENT'],"MicroMessenger")!==false){
        return true;
    }else{
        return false;
    }
}

/**
 * 获取用户浏览器型号。新加浏览器，修改代码，增加特征字符串.把IE加到12.0 可以使用5-10年了.
 */
function getBrowser(){
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'Maxthon')) {
        $browser = 'Maxthon';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 12.0')) {
        $browser = 'IE12.0';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 11.0')) {
        $browser = 'IE11.0';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10.0')) {
        $browser = 'IE10.0';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 9.0')) {
        $browser = 'IE9.0';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 8.0')) {
        $browser = 'IE8.0';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7.0')) {
        $browser = 'IE7.0';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.0')) {
        $browser = 'IE6.0';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'NetCaptor')) {
        $browser = 'NetCaptor';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape')) {
        $browser = 'Netscape';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Lynx')) {
        $browser = 'Lynx';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera')) {
        $browser = 'Opera';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome')) {
        $browser = 'Google';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
        $browser = 'Firefox';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) {
        $browser = 'Safari';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'iphone') || strpos($_SERVER['HTTP_USER_AGENT'], 'ipod')) {
        $browser = 'iphone';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'ipad')) {
        $browser = 'iphone';
    } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'android')) {
        $browser = 'android';
    } else {
        $browser = 'other';
    }
    return $browser;
}

/**
 * 获取指定时间当天的0：00：00或23：59：59的时间戳
 * @param $time 格式化的时间字符串
 * @param int $type 标志，1=获取0：00：00的时间戳，其他=获取23：59：59的时间戳
 * @return int
 */
function getTime($time,$type=1){
    $time = strtotime($time);
    if($type==1){
        return mktime(0,0,0,date('m',$time),date('d',$time),date('Y',$time));
    } else {
        return mktime(23,59,59,date('m',$time),date('d',$time),date('Y',$time));
    }
}

//删除目录及文件夹
function deletedir($path,$isecho=false){
    if(is_dir($path)){
        $path=rtrim($path,"/");
        $arr=_scandir($path);
        if(count($arr)>2){
            foreach ($arr as $k=>$v){
                if($v!=='.'&&$v!=='..'){
                    if(is_dir($path.'/'.$v)){
                        deletedir($path.'/'.$v,$isecho);
                    }else{
                        if(file_exists($path.'/'.$v)){
                            if(unlink($path.'/'.$v)){
                                if($isecho) echo '<p><span style="color:#093">'.L('file_del_su').':&nbsp"'.$path.'/'.$v.'"&nbsp</span></p>';
                            }else{
                                if($isecho) echo '<P><span style="color:#F00">'.L('file_del_er').':&nbsp"'.$path.'/'.$v.'"&nbsp['.L('KNNOAU').']</span></P>';
                            }
                        }else{
                            if($isecho) echo '<p><span style="color:#FF8000">'.L('file_del_er').':&nbsp"'.$path.'/'.$v.'"&nbsp['.L('nofile').']</span></p>';
                        }
                    }
                    deletedir($path.'/'.$v,$isecho);
                }
            }
        }else{
            if(rmdir($path)){
                if($isecho) echo '<p><span style="color:#093">'.L('dir_del_su').':&nbsp"'.$path.'"&nbsp</span></p>';
            }else{
                if($isecho) echo '<p><span style="color:#F00">'.L('dir_del_er').':&nbsp"'.$path.'"&nbsp['.L('DIRKNNOAU').']</span></p>';
            }
        }
    }else{
        if(file_exists($path)){
            if(unlink($path)){
                if($isecho) echo '<p><span style="color:#093">'.L('file_del_su').':&nbsp"'.$path.'"&nbsp</span></p>';
            }else{
                if($isecho) echo '<P><span style="color:#F00">'.L('file_del_er').':&nbsp"'.$path.'"&nbsp['.L('KNNOAU').']</span></P>';
            }
        }else{
            if($isecho) echo '<p><span style="color:#FF8000">'.L('file_del_er').':&nbsp"'.$path.'"&nbsp['.L('nofile').']</span></p>';
        }
    }
}

//扫描目录 $dir 需要扫描目录， $file 是否只显示文件
function _scandir($dir,$file=false){
    $dh  = opendir($dir);
    while (false !== ($filename = readdir($dh))) {
        if($file){
            if(!is_dir($dir.'/'.$filename))  $files[] = $filename;
        }else{
            $files[] = $filename;
        }
    }
    closedir($dh);
    return  $files;
}

/**
 * 字符串转数组
 * @param $string 字符串
 * @param string $format 分隔格式
 * @return array|bool
 */
function str2arr($string,$format = ','){
    if(empty($string)) return '';
    return explode($format,$string);
}

/**
 * 数组转字符串
 * @param $array
 * @param string $format
 * @return bool|string
 */
function arr2str($array,$format = ','){
    if(empty($array)) return false;
    return implode($format,$array);
}


/**
 * 传统形式显示无限极分类树
 * @param array $data 树形结构数据
 * @param string $stable 分类表名或表标识符
 * @param integer $level 添加子分类层级，默认为0，则可以添加无限子分类
 * @param bool $isDelAble 是否允许删除
 * @param bool $isStatusAble  是否允许改变状态
 * @param bool $isAllowSub  是否允许添加子分类
 * @param bool $isAllowSort  是否允许排序
 * @param string $titleField  显示字段名称
 * @param bool $is_ul_show  ul是否显示或隐藏，调用函数时，不需要传入值。
 * @param integer $times 用于记录递归层级的次数，默认为1，调用函数时，不需要传入值。
 * @return string 树形结构的HTML数据
 */
function showTreeCategory($data,$stable,$level = 0,$titleField='title',$isDelAble=true,$isStatusAble=true,$isAllowSub=true,$isAllowSort=true,$is_ul_show=true,$times = 1){
    if($is_ul_show){
        $html = '<ul>';
    } else {
        $html = '<ul style="display:none;">';
    }

    foreach($data as $val) {
        // 判断是否有符号
        if($val['child']){
            $icon = 'on.png';
        } else if($times != 1 ){
            $icon = 'off.png';
        } else {
            $icon = 'off.png';
        }

        $html .= '<li>';
        $html .= '<p>';

        if($icon){
            $html .= '<img id="img_'.$val['id'].'" src="'.C('TMPL_PARSE_STRING.__PUBLIC__').'/Admin/images/'.$icon.'" />';
        }
        $html .= '<span class="title">'.$val[$titleField].'</span>';

        //操作
        $html .= '<span class="c3">';

        //国家管理单独处理
        $addCountryHtml = '';
        $countryRelationHtml = '';
        $countryRecommendHtml = '';
        if($stable == 'country'){
            $countryLevel = 'data-level='.$val['level'];
            $addSubText = '';
            switch($val['level']){
                case 1:
                    $addSubText = '添加国家';
                    break;

                case 2:
                    $addSubText = '添加州（省）';
                    $addCountryHtml = '&nbsp;&nbsp;-&nbsp;&nbsp;<a href="javascript:;" class="add_sub_category" data-level="'.($val['level']+1).'" data-mark="'.$stable.'" data-id="'.$val['id'].'">添加城市</a>';
                    $countryRelationHtml = '&nbsp;&nbsp;-&nbsp;&nbsp;<a href="country?id='.$val['id'].'" class="relation_set" data-mark="'.$stable.'" data-id="'.$val['id'].'">设置国家相关</a>';
                    $recommendText = $val['is_recommend'] == 1 ? '取消推荐' : '推荐';
                    $countryRecommendHtml = '&nbsp;&nbsp;-&nbsp;&nbsp;<a href="javascript:;" class="recommend_set" data-mark="'.$stable.'" data-id="'.$val['id'].'" data-recommend="'.$val['is_recommend'].'">'.$recommendText.'</a>';
                    unset($recommendText);
                    break;

                case 3:
                    $addSubText = '添加城市';
                    break;
            }
        } else {
            $countryLevel = ' ';
            $addSubText = '添加子类';
        }

        if($stable == 'item_category'){
            $typeText = 'data-type="'.$val['type'].'"';
        } else {
            $typeText = '';
        }

        $isAllowItemCateSub = true;
        if($stable == 'item_category'){
            if($val['layer'] == 1){
                $isAllowItemCateSub = false;
            }
        }

        $separator = '';
        if($isAllowSub && $isAllowItemCateSub && ($level == 0 || $times < $level) && ($stable == 'country' ? $val['level'] < $level : true)) {
            $html .= $separator.'<a href="javascript:;" class="add_sub_category" '.$countryLevel. ' '. $typeText .' data-mark="'.$stable.'" data-hierarchy="'.$times.'" data-id="'.$val['id'].'">'.$addSubText.'</a>';
            $separator = '&nbsp;&nbsp;-&nbsp;&nbsp;';
        }
        $html .= $addCountryHtml;
        $html .= $separator.'<a href="javascript:void(0);" class="edit_category" '.$countryLevel. ' '. $typeText .' data-mark="'.$stable.'" data-hierarchy="'.$times.'" data-id="'.$val['id'].'">修改</a>';
        $separator = '&nbsp;&nbsp;-&nbsp;&nbsp;';
        if($isStatusAble){
            $statusButtonText = $val['status'] == 1 ? '禁用' : '启用';
            $html .= $separator.'<a href="javascript:void(0);" class="status_category" '.$countryLevel. ' '. $typeText .' data-id="'.$val['id'].'" data-hierarchy="'.$times.'" data-mark="'.$stable.'" data-status="'.$val['status'].'">'.$statusButtonText.'</a>';
        }
        if($stable == 'item_category' && $val['type'] == 1 && $val['pid']==1){
            $html .= $separator.'<a href="javascript:void(0);" class="relation_country" '. $typeText .' data-id="'.$val['id'].'" data-hierarchy="'.$times.'" data-mark="'.$stable.'">设置关联国家</a>';
        }
        if($isDelAble){
            $html .= $separator.'<a href="javascript:void(0);" class="del_category" '.$countryLevel. ' '. $typeText .' data-mark="'.$stable.'" data-hierarchy="'.$times.'" data-id="'.$val['id'].'">删除</a>';
        }
        $html .= $countryRecommendHtml;
        $html .= $countryRelationHtml;
        $html .= '</span>';

        //排序
        if($isAllowSort){
            $html .= '<span class="c2 center">';
            $html .= '<a href="javascript:;" data-mark="'.$stable. '" '. $typeText .' data-id="'.$val['id'].'" class="ico_top mr5"></a>';
            $html .= '<a href="javascript:;" data-mark="'.$stable. '" '. $typeText .' data-id="'.$val['id'].'" class="ico_btm"></a>';
            $html .= '</span>';
        }

        $html .= '</p>';

        if($val['child']){
            $html .= showTreeCategory($val['child'],$stable,$level,$titleField,$isDelAble,$isStatusAble,$isAllowSub,$isAllowSort,false,$times + 1);
        }

        $html .= '</li>';
    }

    $html .= '</ul>';

    return $html;
}

/**
 * 手机正则验证
 * @param $mobile
 * @return bool
 */
function mobileRegular($mobile){
    if(checkRegx(\Common\Org\Util\InputData::$mobile_reg,$mobile)){
        return true;
    }else{
        return false;
    }
}

/**
 * 获取地区等分类的名字（含全名）,多个由英文逗号隔开
 * @param $path 路径
 * @param $table 表名（不含前缀），如area
 * @param string $delimiter 分隔符，如-
 * @param int $layer 获取的层级，4=全部，3=去除顶层，2=去除顶层和最后一层，1=只取最后一层
 */
function getFullNameByPath($path,$table='',$delimiter=' ',$layer=3){
    return D('Common/Area')->getFullNameByAreaCode($path,$layer,$delimiter);
}

/**
 *  根据地址获取经纬度
 * @param $address 详细地址
 * @param string $key 申请的key值
 * @return bool array (lng经度  lat纬度)
 */
function getAddressLocation($address,$key='iWG1OkTp12E9zjxvYnasehGD'){
    if(empty($address)) return false;
    $address = preg_replace('/\s*/', '', $address);
    $url = 'http://api.map.baidu.com/geocoder/v2/?address='.$address.'&output=json&ak='.$key;
    $result = file_get_contents($url);
    $data = json_decode($result,true);
    $location = $data['result']['location'];
    return $location;
}

/**
 * 根据经纬度获取地址
 * @param $location(纬度,经度)
 * @param string $key
 * @return bool
 */
function getAddressByLocation($location,$key='QdfXLGhCAhnYPvP29XSWgQMAjXyVIQ0p'){
    if(empty($location)) return false;
    $url = "http://api.map.baidu.com/geocoder/v2/?ak={$key}&location={$location}&output=json&pois=1";
    $res = file_get_contents($url);
    $data = json_decode($res,true);
    return $data['result']['formatted_address'];
}

//获取图片完整链接路径, $img_type= big | mid | small
function showImage($img,$alias,$uid='',$img_type=''){
    if($img_type=='small'){
        $size = 3;
    } else if($img_type=='mid'){
        $size = 2;
    } else {
        $size = 1;
    }
    return getImgUrl($img,$uid,$alias,$size,1);
}

/**
 * 邮件正则验证
 * @param $email 邮件
 * @return bool
 */
function emailRegular($email){
    if(checkRegx("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/",$email)){
        return true;
    }else{
        return false;
    }
}

/**
 * https请求（支持GET和POST）
 * @param $url 请求URL
 * @param null $data 需提交的数据
 * @return mixed
 */
function https_request($url,$data = null,$type=''){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if(!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    if($type==1){
        curl_setopt($curl, CURLOPT_HEADER, true);
    }
    //curl_setopt($curl, CURLOPT_NOBODY, true);

    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 金额验证
 * @param $money 金额
 * @return bool
 */
function moneyRegx($money){
    if(empty($money)) return false;
    if(checkRegx("/^[0-9]+(.[0-9]{1,2})?$/",$money)){
        return true;
    }else{
        return false;
    }
}

/**
 * QQ正则
 * @param $qq
 * @return bool
 */
function qqRegx($qq){
    if(empty($qq)) return false;
    if(checkRegx("/^[1-9]\d{4,11}$/",$qq)){
        return true;
    }else{
        return false;
    }
}

function urlRegx($url){
    if(empty($url)) return false;
    if(checkRegx("/^http:\/\/[A-Za-z0-9-]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"])*$/",$url)){
        return true;
    }else{
        return false;
    }
}

/**
 *
+--------------------------------------------------------------------
 * Description 友好显示时间
+--------------------------------------------------------------------
 * @param int $time 要格式化的时间戳 默认为当前时间
+--------------------------------------------------------------------
 * @return string $text 格式化后的时间戳
+--------------------------------------------------------------------
 * @author yijianqing
+--------------------------------------------------------------------
 */
function mdate($time = NULL) {
    $time = $time === NULL || $time > time() ? time() : intval($time);
    $t = time() - $time; //时间差 （秒）
    if ($t == 0)
        $text = '刚刚';
    elseif ($t < 60)
        $text = $t . '秒前'; // 一分钟内
    elseif ($t < 60 * 60)
        $text = floor($t / 60) . '分钟前'; //一小时内
    elseif ($t < 60 * 60 * 24)
        $text = floor($t / (60 * 60)) . '小时前'; // 一天内
    elseif ($t < 60 * 60 * 24 * 3)
        $text = floor($time/(60*60*24)) ==1 ?'昨天 ' . date('H:i', $t) : '前天 ' . date('H:i', $time) ; //昨天和前天
    elseif ($t < 60 * 60 * 24 * 30)
        $text = date('m月d日 H:i', $time); //一个月内
    elseif ($t < 60 * 60 * 24 * 365)
        $text = date('m月d日', $time); //一年内
    else
        $text = date('Y年m月d日', $time); //一年以前
    return $text;
}

/**
 * 获取文档的完整URL
 * @param $img 文档文件名
 * @param string $uid  用户UID
 * @param $alias 附件配置别名
 * @return string
 */
function getFileUrl($img,$uid='',$alias){
    if(empty($img) || empty($alias)) return '';
    $attach = get_attach($alias,$uid);
    if(empty($attach)) return '';
    return  $attach['img_root'].$img;
}

/**
 * 获取时间
 * @param $time
 * @return bool|int
 */
function getMkTime($time){
    if(empty($time)) return false;
    $year = toDate($time,'Y');
    $month = toDate($time,'m');
    $day = toDate($time,'d');
    return mktime(23,59,59,$month,$day,$year);
}

/**
 * 计算两点的距离
 * @param $from 起点
 * @param $to  终点
 */
function getDistance($from,$to,$key='ZJ6BZ-BVGRP-6RWDZ-L5QAF-SW2EF-L6FTV'){
    $url = 'http://apis.map.qq.com/ws/distance/v1/?mode=driving&from='.$from.'&to='.$to.'&key='.$key;
    $result = file_get_contents($url);
    $data = json_decode($result,true);
    if($data['status'] == 0){
        return $data['result']['elements'][0]['distance'];
    }else{
        return $data['message'];
    }
}

/**
 * 距离格式化
 * @param $distance
 * @return bool|string
 */
function distanceFormat($distance){
    if(empty($distance)) return false;
    if($distance < 1000){
        return $distance .'米';
    }else{
        $result = $distance / 1000;
        return number_format($result,1).'千米';
    }
}

/**
 * 生成唯一订单号
 * @return string
 */
function getOrderNo(){
    $year_code = array('A','B','C','D','E','F','G','H','I','J');
    return $year_code[(intval(date('Y'))-2015)%10].strtoupper(dechex(date('m'))).date('d').substr(time(),-5).substr(microtime(),2,5).sprintf('d',rand(0,99));
}

/**
 * 获取经纬度(根据地质)
 * @param $address
 * @param string $key
 * @return bool
 */
function getLocationByAddress($address,$key='RYQU9U0jGmcjgc6rVX5dLgmbgi4BVn36'){
    if(empty($address)) return false;
    $url = "http://api.map.baidu.com/geocoder/v2/?address={$address}&output=json&ak={$key}";
    $data = file_get_contents($url);
    $result = json_decode($data,true);
    if($result['status'] == 0){
        return array(
            'lng'=>$result['result']['location']['lng'],
            'lat'=>$result['result']['location']['lat']
        );
    }
}